package com.demo.Main.StageOne;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 服务器列表会放到一个`server.txt`文件中，
 * 请从`server.txt`文件中读取到服务器列表并发送`http`请求确定服务器上的接收文件服务是否正常，
 * 并在控制台显示检测结果
 *
 */

public class Demo3 {
    public static void main(String[] args) {
        A(new File("localfile/server.txt"));
    }
    private static void A(File file){
        //创建一个线程池
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(
                5,        //核心线程数
                10,    //最大线程数
                5,     //等待时间
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),//阻塞队列
                new ThreadPoolExecutor.DiscardOldestPolicy()//溢出处理决策
        );
       //执行线程任务
        tpe.execute(() -> {
            try (FileReader fis = new FileReader(file);
                 BufferedReader br = new BufferedReader(fis)) {
                while (br.ready()) {
                    //分行读取文件
                    String s = br.readLine();
                    // boolean b = s.startsWith(" ");
                    if ("".equals(s))
                    {
                        continue;
                    }
                    //访问从文件中读取的网址
                    HttpRequest httpRequest = HttpRequest.get(s).timeout(2000);
                    HttpResponse execute = null;
                    try {
                        execute = httpRequest.execute();
                    } catch (Exception e) {
                        System.err.println(s + "无法访问网络");
                        continue;
                    }
                    int status = execute.getStatus();
                    if (status == 200) {
                        System.out.println(s + " 网站访问成功");
                    } else {
                        System.err.println(s + " 网站访问失败");
                    }
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        tpe.shutdown();
        //任务结束
    }

}
